package pl.edu.pw.ee.buildcity.notifiers;

import org.apache.log4j.Logger;
import org.springframework.ui.velocity.VelocityEngineUtils;
import pl.edu.pw.ee.buildcity.entities.BuildActivity;
import pl.edu.pw.ee.buildcity.gg.GGService;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Mateusz
 * @since 2010-02-14
 */
public class GGNotifier extends AbstractNotifier {

	private static final Logger log = Logger.getLogger(GGNotifier.class);

	private static final String GG_NOTIFICATION_TEMPLATE = "build-notification-gg-msg-template.vm";

	@Resource(name = "ggService")
	private GGService ggService;

	@Override
	protected void notifyEndOfBuild(List<String> recipients, BuildActivity buildActivity) throws CouldNotNotifyException {
		for (String recipient : recipients) {
			sendGGMessage(recipient, buildActivity);
		}
	}

	private void sendGGMessage(String recipient, BuildActivity buildActivity) {
		try {
			int uin = Integer.parseInt(recipient);
			Map model = createModel(buildActivity);
			String msg = fillTemplate(GG_NOTIFICATION_TEMPLATE, model);
			ggService.sendMessage(uin, msg);
		} catch (Exception e) {
			CouldNotNotifyException notifyException = new CouldNotNotifyException(recipient, e);
			log.error(notifyException.getMessage(), notifyException);
			throw notifyException;
		}
	}

	private Map createModel(BuildActivity buildActivity) {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("buildActivity", buildActivity);
		return model;
	}

	private String fillTemplate(String templateFileName, Map model) {
		String mergedTemplate = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateFileName, model);
		return mergedTemplate;
	}
}
